/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.controller;

import com.googlecode.bambole.controller.util.ConfigurationUtil;
import com.googlecode.bambole.controller.util.ConnectionUtil;
import com.googlecode.bambole.domain.OrderHeader;
import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.LogoUtil;
import com.googlecode.bambole.controller.util.PaginationUtil;
import com.googlecode.bambole.domain.User;
import com.googlecode.bambole.facade.OrderHeaderFacade;
import com.googlecode.bambole.util.DiscountUtil;
import com.googlecode.bambole.util.SearchUtil;
import java.io.IOException;

import java.io.Serializable;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import org.apache.commons.lang3.text.WordUtils;

@Named("orderHeaderController")
@SessionScoped
public class OrderHeaderController implements Serializable {

    private OrderHeader current;

    private DataModel items = null;

    @EJB
    private com.googlecode.bambole.facade.OrderHeaderFacade ejbFacade;

    @Inject
    private com.googlecode.bambole.controller.OrganizationController organizationController;

    @Inject
    private com.googlecode.bambole.controller.PaymentTermController paymentTermController;

    @Inject
    private com.googlecode.bambole.controller.OrderItemController orderItemController;

    @Inject
    private com.googlecode.bambole.controller.AddressController addressController;

    @Inject
    private com.googlecode.bambole.controller.ChannelController channelController;

    @Inject
    private com.googlecode.bambole.controller.StatusController statusController;

    @Inject
    private com.googlecode.bambole.controller.PersonController personController;

    @Inject
    private com.googlecode.bambole.controller.TypeController typeController;

    private PaginationUtil pagination;
    private Object[] searchArray = new Object[9];
    private String freightEstimatedTransitTimeSearch;
    private String estimatedDeliveryDateSearch;
    private String freightEstimatedCostSearch;
    private String documentSearch;
    private String productAmountSearch;
    private String productDiscountSearch;
    private String discountedProductAmountSearch;
    private String amountSearch;
    private String discountSearch;
    private String totalDiscountSearch;
    private String orderedSearch;
    private String query;
    private int selectedItemIndex;
    private int recordCount;
    private boolean searchMode = false;

    public OrderHeaderController() {
    }

    public OrderHeader getSelected() {
        if (current == null) {
            current = new OrderHeader();
        }
        return current;
    }

    public void setSelected(OrderHeader current) {
        this.current = current;
    }

    private OrderHeaderFacade getFacade() {
        return ejbFacade;
    }

    public boolean isPaginationFromSearch() {
        return !getQuery().equals(getDefaultQuery());
    }

    public PaginationUtil getPagination() {
        if (pagination == null) {
            pagination = new PaginationUtil(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count(getQuery(), searchArray);
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getQuery(), searchArray));
                }
            };
        }
        return pagination;
    }

    public String refreshList() {
        searchArray = new Object[9];
        query = null;
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareList() {
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        recordCount = getFacade().count(getQuery(), searchArray);

        return "view.xhtml?faces-redirect=true";
    }

    public String prepareCreate() {

        searchMode = false;

        current = new OrderHeader();

        current.setType(typeController.getDefaultItem());
        current.setStatus(statusController.getOpeningStatus());
        current.setChannel(channelController.getDefaultItem());
        current.setPaymentTerm(paymentTermController.getDefaultItem());
        current.setOrdered(new Date());

        return "create.xhtml?faces-redirect=true";
    }

    public String create() {

        if (!validateRecord()) {
            return null;
        }

        Date date = new Date();
        User user = (User) JsfUtil.getSessionParameter("user");
        current.setCreated(date);
        current.setCreatedBy(user);
        current.setUpdated(date);
        current.setUpdatedBy(user);
        current.setDocument(getFacade().getNextDocument());

        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String prepareEdit() {
        searchMode = false;
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));

            return null;
        }
        return "edit.xhtml?faces-redirect=true";
    }

    public String update() {

        if (!validateRecord()) {
            return null;
        }

        current.setUpdated(new Date());
        current.setUpdatedBy((User) JsfUtil.getSessionParameter("user"));

        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String destroy() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }
        performDestroy();
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public OrderHeader getOrderHeader(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex + pagination.getPageFirstItem();
    }

    public boolean isHasNextRecord() {
        return selectedItemIndex + 2 <= recordCount;
    }

    public boolean isHasPreviousRecord() {
        return selectedItemIndex > 0;
    }

    public String nextItem() {

        selectedItemIndex++;

        if (selectedItemIndex < recordCount) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    public String previousItem() {

        selectedItemIndex--;

        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    private boolean validateRecord() {

        boolean retVal = true;

        if (current.getStatus().isClosing()) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("ClosedOrdersCannotBeChanged"));

            retVal = false;
        }

        if (current.getFreightEstimatedCost() < 0) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("FreightEstimatedCostCannotBeNegative"));

            retVal = false;
        }

        if (current.getFreightEstimatedTransitTime() != null && current.getFreightEstimatedTransitTime() < 0) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("FreightEstimatedTransitTimeCannotBeNegative"));

            retVal = false;
        }

        if (current.getDiscount() < 0) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("DiscountCannotBeNegative"));

            retVal = false;
        }

        if (current.getOrderItemList() == null || current.getOrderItemList().isEmpty()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("OrderWithoutItems"));
        }

        return retVal;
    }

    private String getQuery() {
        return query == null ? getDefaultQuery() : query;
    }

    private String getDefaultQuery() {
        return "SELECT o FROM OrderHeader o";
    }

    public String prepareSearch() {
        searchMode = true;

        query = getDefaultQuery();

        searchArray = new Object[9];

        orderedSearch = null;
        documentSearch = null;
        freightEstimatedCostSearch = null;
        estimatedDeliveryDateSearch = null;
        freightEstimatedTransitTimeSearch = null;
        amountSearch = null;
        discountSearch = null;
        productAmountSearch = null;
        productDiscountSearch = null;
        discountedProductAmountSearch = null;
        totalDiscountSearch = null;

        current = new OrderHeader();

        return "search.xhtml?faces-redirect=true";
    }

    public String performSearch() {

        searchMode = false;

        boolean queryAddAnd = false;

        boolean queryContainsErrors = false;

        query = getDefaultQuery();

        if ((getDocumentSearch() != null && !getDocumentSearch().isEmpty())
                || (current.getReference() != null && !current.getReference().isEmpty())
                || current.getType() != null || current.getStatus() != null || current.getChannel() != null
                || current.getPaymentTerm() != null || current.getOrganization() != null
                || (getProductAmountSearch() != null && !getProductAmountSearch().isEmpty())
                || (getProductDiscountSearch() != null && !getProductDiscountSearch().isEmpty())
                || (getAmountSearch() != null && !getAmountSearch().isEmpty())
                || (getDiscountSearch() != null && !getDiscountSearch().isEmpty())
                || (getTotalDiscountSearch() != null && !getTotalDiscountSearch().isEmpty())
                || (getDiscountedProductAmountSearch() != null && !getDiscountedProductAmountSearch().isEmpty())
                || (current.getDescription() != null && !current.getDescription().isEmpty())
                || current.getAddress() != null || current.getPerson() != null
                || (getOrderedSearch() != null && !getOrderedSearch().isEmpty())
                || (getEstimatedDeliveryDateSearch() != null && !getEstimatedDeliveryDateSearch().isEmpty())
                || current.getFreightOrganization() != null || current.getFreightOrganizationPerson() != null
                || (getFreightEstimatedCostSearch() != null && !getFreightEstimatedCostSearch().isEmpty())
                || (getFreightEstimatedTransitTimeSearch() != null && !getFreightEstimatedTransitTimeSearch().isEmpty())) {

            query = query + " WHERE ";

            if (getDocumentSearch() != null && !getDocumentSearch().isEmpty()) {
                String documentSearchClause = SearchUtil.getQueryClause("o.document", getDocumentSearch(), 'n', queryAddAnd);
                if (!documentSearchClause.equals("*")) {
                    query = query + documentSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (current.getReference() != null && !current.getReference().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.reference LIKE \'%" + current.getReference() + "%\'";
            }

            if (current.getType() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.type = :type";
                searchArray[0] = current.getType();
            }

            if (current.getStatus() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.status = :status";
                searchArray[1] = current.getStatus();
            }

            if (current.getChannel() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.channel = :channel";
                searchArray[2] = current.getChannel();
            }

            if (current.getPaymentTerm() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.paymentTerm = :paymentTerm";
                searchArray[3] = current.getPaymentTerm();
            }

            if (getProductAmountSearch() != null && !getProductAmountSearch().isEmpty()) {
                String documentSearchClause = SearchUtil.getQueryClause("o.productAmount", getProductAmountSearch(), 'n', queryAddAnd);
                if (!documentSearchClause.equals("*")) {
                    query = query + documentSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getDiscountedProductAmountSearch() != null && !getDiscountedProductAmountSearch().isEmpty()) {
                String documentSearchClause = SearchUtil.getQueryClause("o.discountedProductAmount", getDiscountedProductAmountSearch(), 'n', queryAddAnd);
                if (!documentSearchClause.equals("*")) {
                    query = query + documentSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getProductDiscountSearch() != null && !getProductDiscountSearch().isEmpty()) {
                String documentSearchClause = SearchUtil.getQueryClause("o.productDiscount", getProductDiscountSearch(), 'n', queryAddAnd);
                if (!documentSearchClause.equals("*")) {
                    query = query + documentSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getAmountSearch() != null && !getAmountSearch().isEmpty()) {
                String documentSearchClause = SearchUtil.getQueryClause("o.amount", getAmountSearch(), 'n', queryAddAnd);
                if (!documentSearchClause.equals("*")) {
                    query = query + documentSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getDiscountSearch() != null && !getDiscountSearch().isEmpty()) {
                String documentSearchClause = SearchUtil.getQueryClause("o.discount", getDiscountSearch(), 'n', queryAddAnd);
                if (!documentSearchClause.equals("*")) {
                    query = query + documentSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getTotalDiscountSearch() != null && !getTotalDiscountSearch().isEmpty()) {
                String documentSearchClause = SearchUtil.getQueryClause("o.totalDiscount", getTotalDiscountSearch(), 'n', queryAddAnd);
                if (!documentSearchClause.equals("*")) {
                    query = query + documentSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (current.getOrganization() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.organization = :organization";
                searchArray[4] = current.getOrganization();
            }

            if (current.getDescription() != null && !current.getDescription().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.description LIKE \'%" + current.getDescription() + "%\'";
            }

            if (current.getAddress() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.address = :address";
                searchArray[5] = current.getAddress();
            }

            if (current.getPerson() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.person = :person";
                searchArray[6] = current.getPerson();
            }

            if (getOrderedSearch() != null && !getOrderedSearch().isEmpty()) {
                String orderedSearchClause = SearchUtil.getQueryClause("FUNC(\'DATE\',o.ordered)", getOrderedSearch(), 'd', queryAddAnd);
                if (!orderedSearchClause.equals("*")) {
                    query = query + orderedSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getEstimatedDeliveryDateSearch() != null && !getEstimatedDeliveryDateSearch().isEmpty()) {
                String estimatedDeliveryDateSearchClause = SearchUtil.getQueryClause("FUNC(\'DATE\',o.estimatedDeliveryDate)", getEstimatedDeliveryDateSearch(), 'd', queryAddAnd);
                if (!estimatedDeliveryDateSearchClause.equals("*")) {
                    query = query + estimatedDeliveryDateSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (current.getFreightOrganization() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.freightOrganization = :freightOrganization";
                searchArray[7] = current.getFreightOrganization();
            }

            if (current.getFreightOrganizationPerson() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.freightOrganizationPerson = :freightOrganizationPerson";
                searchArray[8] = current.getFreightOrganizationPerson();
            }

            if (getFreightEstimatedCostSearch() != null && !getFreightEstimatedCostSearch().isEmpty()) {
                String freightEstimatedCostSearchClause = SearchUtil.getQueryClause("p.price", getFreightEstimatedCostSearch(), 'n', queryAddAnd);
                if (!freightEstimatedCostSearchClause.equals("*")) {
                    query = query + freightEstimatedCostSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getFreightEstimatedTransitTimeSearch() != null && !getFreightEstimatedTransitTimeSearch().isEmpty()) {
                String freightEstimatedTransitTimeSearchClause = SearchUtil.getQueryClause("p.price", getFreightEstimatedTransitTimeSearch(), 'n', queryAddAnd);
                if (!freightEstimatedTransitTimeSearchClause.equals("*")) {
                    query = query + freightEstimatedTransitTimeSearchClause;
                } else {
                    queryContainsErrors = true;
                }
            }
        }

        if (queryContainsErrors) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidSearchCriteria"));

            return prepareSearch();
        } else {
            recreatePagination();
            recreateModel();

            return "list.xhtml?faces-redirect=true";
        }
    }

    public SelectItem[] getSelectType() {
        return typeController.getItemsAvailableSelectOne(searchMode);
    }

    public SelectItem[] getSelectStatus() {
        return statusController.getItemsAvailableSelectOne(searchMode);
    }

    public SelectItem[] getSelectChannel() {
        return channelController.getItemsAvailableSelectOne(searchMode);
    }

    public SelectItem[] getSelectOrganization() {
        return organizationController.getItemsAvailableSelectOne(searchMode);
    }

    public SelectItem[] getSelectAddress() {
        return addressController.getItemsAvailableByOrganizationSelectOne(current.getOrganization(), searchMode);
    }

    public SelectItem[] getSelectPerson() {
        return personController.getItemsAvailableByOrganizationSelectOne(current.getOrganization(), searchMode);
    }

    public SelectItem[] getSelectPaymentTerm() {
        return paymentTermController.getItemsAvailableSelectOne(searchMode);
    }

    public SelectItem[] getSelectFreightOrganization() {
        return organizationController.getFreightItemsAvailableSelectOne(searchMode);
    }

    public SelectItem[] getSelectFreightOrganizationPerson() {
        return personController.getItemsAvailableByOrganizationSelectOne(current.getFreightOrganization(), searchMode);
    }

    public void amountUpdate(ValueChangeEvent e) {
        double newAmount;
        if (e.getNewValue() instanceof Long) {
            newAmount = ((Long) e.getNewValue()).doubleValue();
        } else {
            newAmount = (Double) e.getNewValue();
        }
        current.setDiscount(DiscountUtil.calculateDiscount(current.getDiscountedProductAmount(), newAmount));
        totalDiscountUpdate();
    }

    public void discountUpdate(ValueChangeEvent e) {
        double newDiscount;
        if (e.getNewValue() instanceof Long) {
            newDiscount = ((Long) e.getNewValue()).doubleValue();
        } else {
            newDiscount = (Double) e.getNewValue();
        }
        current.setAmount(DiscountUtil.calculateAmount(current.getDiscountedProductAmount(), newDiscount));
        totalDiscountUpdate();
    }

    private void totalDiscountUpdate() {
        current.setTotalDiscount(DiscountUtil.calculateDiscount(current.getProductAmount(), current.getAmount()));
    }

    public void organizationChange() {
        current.setAddress(null);
        current.setPerson(null);
    }

    public void freightOrganizationChange() {
        current.setFreightOrganizationPerson(null);
    }

    public String getDocumentSearch() {
        return documentSearch;
    }

    public String getDocumentSearchOnCreate() {
        return "< " + String.format(JsfUtil.getLocale(), "%,d", getFacade().findMaxDocument()) + " >";
    }

    public void setDocumentSearch(String documentSearch) {
        this.documentSearch = documentSearch;
    }

    public String getOrderedSearch() {
        return orderedSearch;
    }

    public void setOrderedSearch(String orderedSearch) {
        this.orderedSearch = orderedSearch;
    }

    public String getEstimatedDeliveryDateSearch() {
        return estimatedDeliveryDateSearch;
    }

    public void setEstimatedDeliveryDateSearch(String estimatedDeliveryDateSearch) {
        this.estimatedDeliveryDateSearch = estimatedDeliveryDateSearch;
    }

    public String getFreightEstimatedCostSearch() {
        return freightEstimatedCostSearch;
    }

    public void setFreightEstimatedCostSearch(String freightEstimatedCostSearch) {
        this.freightEstimatedCostSearch = freightEstimatedCostSearch;
    }

    public String getFreightEstimatedTransitTimeSearch() {
        return freightEstimatedTransitTimeSearch;
    }

    public void setFreightEstimatedTransitTimeSearch(String freightEstimatedTransitTimeSearch) {
        this.freightEstimatedTransitTimeSearch = freightEstimatedTransitTimeSearch;
    }

    public String getProductAmountSearch() {
        return productAmountSearch;
    }

    public void setProductAmountSearch(String productAmountSearch) {
        this.productAmountSearch = productAmountSearch;
    }

    public String getProductDiscountSearch() {
        return productDiscountSearch;
    }

    public void setProductDiscountSearch(String productDiscountSearch) {
        this.productDiscountSearch = productDiscountSearch;
    }

    public String getAmountSearch() {
        return amountSearch;
    }

    public void setAmountSearch(String amountSearch) {
        this.amountSearch = amountSearch;
    }

    public String getDiscountSearch() {
        return discountSearch;
    }

    public void setDiscountSearch(String discountSearch) {
        this.discountSearch = discountSearch;
    }

    public String getDiscountedProductAmountSearch() {
        return discountedProductAmountSearch;
    }

    public void setDiscountedProductAmountSearch(String discountedProductAmountSearch) {
        this.discountedProductAmountSearch = discountedProductAmountSearch;
    }

    public String getTotalDiscountSearch() {
        return totalDiscountSearch;
    }

    public void setTotalDiscountSearch(String totalDiscountSearch) {
        this.totalDiscountSearch = totalDiscountSearch;
    }

    public String prepareOrderItemList() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        orderItemController.setCurrentOrderHeader(current);

        return "/app/order_item/list.xhtml?faces-redirect=true";
    }

    public void performPrint() throws JRException, IOException, NamingException, SQLException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String fileNameParam = httpServletRequest.getHeader("user-agent").toLowerCase().contains("firefox") ? "filename*" : "filename";

        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        httpServletResponse.setHeader("Content-disposition", "attachment; " + fileNameParam + "=" + URLEncoder.encode(WordUtils.capitalizeFully(current.getType().getName()).replace(" ", ""), "UTF-8") + "_" + current.getDocument() + ".pdf");
        httpServletResponse.setContentType("application/pdf");

        Map reportParameters = new HashMap();
        reportParameters.put(JRParameter.REPORT_LOCALE, ConfigurationUtil.getDefaultLocale());
        reportParameters.put("logo", LogoUtil.getDefaultLogo());
        reportParameters.put("document", current.getDocument());
        reportParameters.put("theme", ConfigurationUtil.getDefaultTheme());
        reportParameters.put("labelType", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Type") + ":");
        reportParameters.put("labelDocument", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Document") + ":");
        reportParameters.put("labelFrom", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("From") + ":");
        reportParameters.put("labelEmail", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Email") + ":");
        reportParameters.put("labelTo", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("To") + ":");
        reportParameters.put("labelDate", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Date") + ":");
        reportParameters.put("labelChannel", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Channel") + ":");
        reportParameters.put("labelDeliveryDate", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("DeliveryDate") + ":");
        reportParameters.put("labelReference", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Reference") + ":");
        reportParameters.put("labelNotes", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Notes") + ":");
        reportParameters.put("labelImage", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Image"));
        reportParameters.put("labelCode", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Code"));
        reportParameters.put("labelNameAndColor", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("NameAndColor"));
        reportParameters.put("labelDimensionAndDescription", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("DimensionAndDescription"));
        reportParameters.put("labelQty", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Qty"));
        reportParameters.put("labelPrice", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Price"));
        reportParameters.put("labelAmount", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Amount"));
        reportParameters.put("labelPaymentTerm", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("PaymentTerm") + ":");
        reportParameters.put("labelFreight", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Freight") + ":");
        reportParameters.put("labelSubtotal", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Subtotal") + ":");
        reportParameters.put("labelTotal", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("Total") + ":");
        reportParameters.put("labelDiscount", ResourceBundle.getBundle("/bundle", ConfigurationUtil.getDefaultLocale()).getString("DiscountAmount") + ":");

        JasperExportManager.exportReportToPdfStream(JasperFillManager.fillReport(FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/report/order.jasper"), reportParameters, ConnectionUtil.getConnection()), httpServletResponse.getOutputStream());

        FacesContext.getCurrentInstance().responseComplete();
    }
}
